
const PEDDING = 'pedding';  // 等待
const FULFILLED = 'fulfilled';  // 成功
const REJECTED = 'rejected';    //  失败

class MyPromise {
    // executor 执行器，相当于promise的回调函数
    constructor(executor) {
        try {
            executor(this.resolve, this.reject)
        } catch (e) {
            this.reject(e);
        }
    }
    // 状态 默认等待
    status = PEDDING;
    // 成功的值
    value = undefined;
    // 失败的值
    reason = undefined;
    // 成功的回调
    successCallback = [];
    // 失败的回调
    failCallback = [];

    resolve = (value) => {
        // promise状态 不可更改，如果状态不是等待，阻止向下执行
        if(this.status !== PEDDING) return;

        this.status = FULFILLED;
        // 状态改变, 赋值
        this.value = value
    }

    reject = (reason) => {
        // promise状态不可更改，如果状态不是等待，阻止向下执行
        if (this.status !== PEDDING) return;
        this.status = REJECTED;
        // 状态改变, 赋值
        this.reason = reason
    }

    then = (successCallback, failCallback) => {
        // 判断参数successCallback, failCallback是否存在
        successCallback ? successCallback : value => value;

        failCallback ? failCallback : reason => { throw reason};

        // ***** 这一块暂时没看明白，需要再看几遍，先抄上*****

        let promsie2 = new MyPromise((resolve, reject) => {
            // 判断状态
            if (this.status === FULFILLED) {
                setTimeout(() => {
                    try {
                        let x = successCallback(this.value);
                        // 判断 x 的值是普通值还是promise对象
                        // 如果是普通值 直接调用resolve 
                        // 如果是promise对象 查看promsie对象返回的结果 
                        // 再根据promise对象返回的结果 决定调用resolve 还是调用reject
                        resolvePromise(promsie2, x, resolve, reject)
                    } catch (e) {
                        reject(e);
                    }
                }, 0)
            } else if (this.status === REJECTED) {
                setTimeout(() => {
                    try {
                        let x = failCallback(this.reason);
                        // 判断 x 的值是普通值还是promise对象
                        // 如果是普通值 直接调用resolve 
                        // 如果是promise对象 查看promsie对象返回的结果 
                        // 再根据promise对象返回的结果 决定调用resolve 还是调用reject
                        resolvePromise(promsie2, x, resolve, reject)
                    } catch (e) {
                        reject(e);
                    }
                }, 0)
            } else {
                // 等待
                // 将成功回调和失败回调存储起来
                this.successCallback.push(() => {
                    setTimeout(() => {
                        try {
                            let x = successCallback(this.value);
                            // 判断 x 的值是普通值还是promise对象
                            // 如果是普通值 直接调用resolve 
                            // 如果是promise对象 查看promsie对象返回的结果 
                            // 再根据promise对象返回的结果 决定调用resolve 还是调用reject
                            resolvePromise(promsie2, x, resolve, reject)
                        } catch (e) {
                            reject(e);
                        }
                    }, 0)
                });
                this.failCallback.push(() => {
                    setTimeout(() => {
                        try {
                            let x = failCallback(this.reason);
                            // 判断 x 的值是普通值还是promise对象
                            // 如果是普通值 直接调用resolve 
                            // 如果是promise对象 查看promsie对象返回的结果 
                            // 再根据promise对象返回的结果 决定调用resolve 还是调用reject
                            resolvePromise(promsie2, x, resolve, reject)
                        } catch (e) {
                            reject(e);
                        }
                    }, 0)
                });
            }
        });
        return promsie2;
    }
    // 不论成功后者失败都会执行
    finally(callback) {
        return this.then(value => {
            return MyPromise.resolve(callback()).then(() => value);
        }, reason => {
            return MyPromise.resolve(callback()).then(() => { throw reason })
        })
    }
    // 捕获promise.then的错误
    // catch 其实是 then(undefined, () => {}) 的语法糖
    catch(failCallback) {
        return this.then(undefined, failCallback)
    }
    /**
     * 实现promise.all方法 这一块也需要再消化消化
     */
    static all(array) {
        let result = [];
        let index = 0;
        return new MyPromise((resolve, reject) => {
            function addData(key, value) {
                result[key] = value;
                index++;
                if (index === array.length) {
                    resolve(result);
                }
            }
            for (let i = 0; i < array.length; i++) {
                let current = array[i];
                if (current instanceof MyPromise) {
                    // promise 对象
                    current.then(value => addData(i, value), reason => reject(reason))
                } else {
                    // 普通值
                    addData(i, array[i]);
                }
            }
        })
    }
    // 实现promise的resove方法
    // Promise.resolve()用于将现有对象转换为Promise对象，从而控制异步流程
    static resolve(value) {
        if (value instanceof MyPromise) return value;
        return new MyPromise(resolve => resolve(value));
    }
}


function resolvePromise(promsie2, x, resolve, reject) {
    if (promsie2 === x) {
        return reject(new TypeError('Chaining cycle detected for promise #<Promise>'))
    }
    // promise 对象
    if (x instanceof MyPromise) {
        x.then(resolve, reject);
    // 普通值
    } else {
        resolve(x);
    }
}
module.exports = MyPromise;